import {createSlice, PayloadAction} from '@reduxjs/toolkit';
import {AppThunk, RootState} from '../../app/store';

export const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

/**
 * 定义数据结构
 */
interface CounterState {
    value: number;
}

/**
 * 初始值
 */
const initialState: CounterState = {
    value: 0,
};

export const counterSlice = createSlice({
    /**
     * 名称空间
     */
    name: 'counter',
    /**
     * 状态初始化
     */
    initialState,
    reducers: {
        /**
         * 增加
         * @param state
         */
        increment: state => {
            state.value += 1;
        },
        /**
         * 减少
         * @param state
         */
        decrement: state => {
            state.value -= 1;
        },
        /**
         * 增加一个指定值
         * @param state
         * @param action
         */
        incrementByAmount: (state, action: PayloadAction<number>) => {
            state.value += action.payload;
        },
    }
});

export const {increment, decrement, incrementByAmount} = counterSlice.actions;

/**
 * 定义一个异步新增操作
 * const dispatch = useDispatch();
 * dispatch(incrementAsync(Number(incrementAmount) || 0))
 * @param amount
 */
export const incrementAsync = (amount: number): AppThunk => async (dispatch, getState) => {
    console.log('延迟10秒')
    await delay(10000)
    console.log('休息好了,干活...')
    // 通过getState可以获取全局store状态
    console.log(getState(), incrementByAmount)
    // dispatch(执行reducer方法) 可以执行对应的reducer方法
    await dispatch(incrementByAmount(amount));
};

/**
 * 获取指定命名空间下的指定属性的状态值, 最终要通过useSelector(selectCount)获取
 * @param state
 */
export const selectCount = (state: RootState) => state.counter.value;

export default counterSlice.reducer;
